#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import <AdSupport/ASIdentifierManager.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <UserNotifications/UserNotifications.h>
#import "TalkingDataSDK.h"
#import "MoLocationManager.h"
#import <StoreKit/StoreKit.h>
#import <AdSupport/AdSupport.h>
#import "FluwxShareHandler.h"
#import "WXApi.h"
@implementation AppDelegate






- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    // 检查网络
   [self checkNetword];
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
   _channel =  [FlutterMethodChannel methodChannelWithName:@"methodChannel" binaryMessenger:controller.binaryMessenger];


    [_channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
//                事件交互 去评论
        if([call.method isEqualToString:@"startLocation"]){
//            开始定位
            [MoLocationManager getMoLocationWithSuccess:^(double lat, double lng){
                NSLog(@"lat lng (%f, %f)", lat, lng);
                [self->_channel invokeMethod:@"location" arguments:@{@"lat": [NSString stringWithFormat:@"%f",lat],@"lng":[NSString stringWithFormat:@"%f",lng]}];
                [MoLocationManager stop];
            } Failure:^(NSError *error){
                [self->_channel invokeMethod:@"locationerror" arguments:error.userInfo];

                [MoLocationManager stop];

            }];
        }else if ([call.method isEqualToString:@"toscore"]){
            [SKStoreReviewController requestReview];
        }
    }];









 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
   center.delegate = self;
   /// 在设备可以接受任何通知之前，调用请求授权会产生提示（是否打开通知，“允许”、“不允许”）：requestAuthorization
   [center requestAuthorizationWithOptions:UNAuthorizationOptionCarPlay | UNAuthorizationOptionSound | UNAuthorizationOptionBadge | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {

       if (granted) {

           dispatch_sync(dispatch_get_main_queue(), ^{
               [[UIApplication sharedApplication]registerForRemoteNotifications];
            });



//           NSLog(@" iOS 10 request notification success");
       }else{
           NSLog(@" iOS 10 request notification fail");
       }
   }];
//    获取到通知传递进来的信息.
    NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];


    [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}


- (void)checkNetword {
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    [task resume];
}



- (void)applicationDidBecomeActive:(UIApplication *)application {

    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized){
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];NSLog(@"%@",idfa);
                [self->_channel invokeMethod:@"udea" arguments:@{@"udea":idfa}];
                

            }
            [TalkingDataSDK init:@"639F2E52D1FF4866BEFE89EB1DBCCDF7" channelId:@"AppStore" custom:@"fjbamz"];
            NSLog(@"=============");
            NSLog(@"%@",[TalkingDataSDK getDeviceId]);
            if([TalkingDataSDK getDeviceId]!= NULL && [TalkingDataSDK getDeviceId].length >0){
                [self->_channel invokeMethod:@"tdud" arguments:@{@"tdud":[TalkingDataSDK getDeviceId]}];
            }

        }
           //

       ];

    } else {// iOS14以下版本依然使用老方法// 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];NSLog(@"%@",idfa);
            [_channel invokeMethod:@"udea" arguments:@{@"udea":idfa}];
        }
        [TalkingDataSDK init:@"639F2E52D1FF4866BEFE89EB1DBCCDF7" channelId:@"AppStore" custom:@"fjbamz"];
        NSLog(@"=============");
        NSLog(@"%@",[TalkingDataSDK getDeviceId]);
        if([TalkingDataSDK getDeviceId]!= NULL && [TalkingDataSDK getDeviceId].length >0){
            [self->_channel invokeMethod:@"tdud" arguments:@{@"tdud":[TalkingDataSDK getDeviceId]}];
        }
      }
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // token 不要本地缓存，当你重新启动、用户换个手机、升级系统都会返回新的token
    // 安全的加密上传到我们的服务器❗️❗️❗️
    NSString *deviceTokenStr = [self deviceTokenStrWithDeviceToken:deviceToken];
    
    NSLog(@"注册远程通知 成功 deviceToken:%@, deviceTokenStr:%@", deviceToken, deviceTokenStr);

    if (deviceToken) {
        // (将器转换成字符串，发送后台)
        /// 为了实现这一点，可以将数组分离到其组件中，再将这些组件转换为十六进制字符串，然后将它们重新连接到字符串
        NSMutableString *deviceTokenString = [NSMutableString string];
        const char *bytes = deviceToken.bytes;
        NSInteger count = deviceToken.length;
        for (int i = 0; i < count; i++) {
            [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
        }
        
        [_channel invokeMethod:@"dfxusf_tokfn" arguments:@{@"dfxusf_tokfn":deviceTokenStr}];
    
    }
    
   
    
    
}
// 将deviceToken转换成字符串
- (NSString *)deviceTokenStrWithDeviceToken:(NSData *)deviceToken {

    NSString *tokenStr;
    
    if (deviceToken) {
        if ([[deviceToken description] containsString:@"length = "]) {  // iOS 13 DeviceToken 适配。
            NSMutableString *deviceTokenString = [NSMutableString string];
            const char *bytes = deviceToken.bytes;
            NSInteger count = deviceToken.length;
            for (int i = 0; i < count; i++) {
                [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
            }
            tokenStr = [NSString stringWithString:deviceTokenString];
        }else {
            tokenStr = [[[[deviceToken description]stringByReplacingOccurrencesOfString:@"<" withString:@""]stringByReplacingOccurrencesOfString:@">" withString:@""]stringByReplacingOccurrencesOfString:@" " withString:@""];
        }
    }
    
    return tokenStr;
}

//前台时收到消息通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandle

@end
